<template>
  <div class="demo-drawer__content">
    <div style="overflow-y: scroll;height: calc(100vh - 350px)">
      <div style="padding:0px 16px 60px 16px;">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="0" title="工位搜索">
            <el-form label-position="top" label-width="100px" size="mini">
              <el-row :gutter="5">
                <el-col :span="12">
                  <el-form-item :label="$t('bs.department')">
                    <el-select v-model="$store.state.advancedSearch.listQuery.dept_id">
                      <el-option v-for="item in depts"  :key="item.id" :value="item.id" :label="item.department_name" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('bs.stream')">
                    <el-select v-model="$store.state.advancedSearch.listQuery.cost_id" :disabled="!$store.state.advancedSearch.listQuery.dept_id">
                      <el-option v-for="item in costs" :key="item.id" :value="item.id" :label="item.department_name" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('bs.productionLine')">
                    <el-select v-model="$store.state.advancedSearch.listQuery.line_id" :disabled="!$store.state.advancedSearch.listQuery.cost_id">
                      <el-option v-for="item in lines" :key="item.id" :value="item.id" :label="item.department_name" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('bs.costCenter')">
                    <el-input v-model="$store.state.advancedSearch.listQuery.name" autocomplete="off" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('bs.supplier')">
                    <el-select v-model="$store.state.advancedSearch.listQuery.supplier_no" clearable>
                      <el-option
                        v-for="(item,k) in supplierList"
                        :key="'b_'+k"
                        :label="item.dict_value"
                        :value="item.dict_key"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('bs.deviceType')">
                    <el-select v-model="$store.state.advancedSearch.listQuery.dev_type" clearable>
                      <el-option
                        v-for="(item,k) in dev_type_option"
                        :key="'b_'+k"
                        :label="item.dict_value"
                        :value="item.dict_key"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('bs.processType')">
                    <!--                        <el-select v-model="$store.state.advancedSearch.listQuery.technology_type" clearable>-->
                    <!--                          <el-option-->
                    <!--                            v-for="(item,k) in technology_type_option"-->
                    <!--                            :key="'c_'+k"-->
                    <!--                            :label="item.technology_name"-->
                    <!--                            :value="item.id"-->
                    <!--                          />-->
                    <!--                        </el-select>-->
                    <technology-select-on-search ref="technologySelectRef"/>
                  </el-form-item>
                </el-col>
                <!--                    <el-col :span="12">-->
                <!--                      <el-form-item label="设备品牌">-->
                <!--                        <el-input v-model="$store.state.advancedSearch.listQuery.name" autocomplete="off" />-->
                <!--                      </el-form-item>-->
                <!--                    </el-col>-->
              </el-row>
            </el-form>
          </el-collapse-item>
          <el-collapse-item name="1" title="工位属性">
            <el-form label-position="top" label-width="100px" size="mini">
              <el-row :gutter="5">
                <el-col v-for="(item,kk) in $store.state.advancedSearch.form.attrinfo" :key="kk" :span="item.inc_type=='3'?24:12">
                  <el-form-item :label="item.name">
                    <el-input
                      v-if="item.inc_type!='2'"
                      v-model="item.attr_val"
                      :type="item.inc_type=='3'?'textarea':'text'"
                    />
                    <el-select v-else v-model="item.attr_val">
                      <el-option v-for="(t,k) in item.list_val" :key="'a_'+k" :label="t.label" :value="t.label" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <div
      class="demo-drawer__footer"
      style="text-align: center;width: 100%;bottom: 0px;padding: 10px;background: #ffffff;border-top:1px solid #f0f2f5"
    >
      <el-button size="mini" @click="cancelForm">取 消</el-button>
      <el-button :loading="loading" size="mini" type="primary" @click="handleFilter">
        {{ loading ? '提交中 ...' : '确 定' }}
      </el-button>
      <el-button size="mini" @click="handleFilterReset">复 位</el-button>
    </div>
    <spare-view ref="sparedetail"/>
    <parts-change-view ref = "partsview" />
     <relocation-view ref="srelocationView" />
    <mis-detail ref="misDetail"/>
  </div>
</template>

<script>
import {
  delFile,
  downBlobFile,
  fetchTree,
  pasteToDir,
  shoucang,
  viewBlobFile,
  getHistory,
  getSearch,
  getShareUrl,
  fetchDict, getPublicTpl, getEmpData, fetchOne, getSpmData
} from '@/api/common'
import { getToken } from '@/utils/auth'
import VueOfficePdf from '@vue-office/pdf'
import clipboard from 'clipboard'
import _ from "lodash"
import VueDraggableResizable from 'vue-draggable-resizable'
import 'vue-draggable-resizable/dist/VueDraggableResizable.css'


import VueOfficeExcel from '@vue-office/excel'
import VueOfficeDocx from '@vue-office/docx'
const calendarTypeOptions = [
  { key: 'By Dep', display_name: 'By Dep' },
  { key: 'By Products', display_name: 'By Products' },
  { key: 'By Process', display_name: 'By Process' },
  { key: 'By Lay out', display_name: 'By Lay out' }
]
import splitPane from 'vue-splitpane'
import waves from '@/directive/waves'
import { fetchList } from '@/api/article'
import FileView from '@/views/Knowledge/fileView.vue'
import Template from '@/views/bs/template.vue'
import { getcost, getDepartment, getlines } from '@/api/department'
import { getTechonlogyCat } from '@/api/technology'
import {addcad, advSearch, getStationAttr} from '@/api/station'
import TechnologySelect from "@/views/technologySelect.vue";
import StationDetail from "@/views/bs/stationDetail.vue";
import {Base64} from "js-base64";
import {getTemplateRoot} from "@/api/template";
import TechnologySelectOnSearch from "@/views/Knowledge/technologySelectOnSearch.vue";
import SpareDetail from "@/views/bs/spareDetail.vue";
import SpareView from "@/views/bs/spareView.vue";
import RelocationView from "@/views/bs/relocationView.vue";
import PartsChangeView from "@/views/bs/partsChangeView.vue";
import MisDetail from "@/views/bs/misDetail.vue"; // waves directive
export default {
  name: 'advancedSearch',
  components: {
    MisDetail,
    PartsChangeView, RelocationView,
    SpareView,
    TechnologySelectOnSearch,
    StationDetail,
    TechnologySelect, Template, FileView, splitPane, VueOfficePdf, VueOfficeExcel, VueOfficeDocx,VueDraggableResizable },
  directives: { waves },
  data() {
    return {
      line_id:'',
      doc_id: 1,
      showShare: false,
      shareurl: '',
      parent_id: 6,
        inc_type:"MAE Info",
        public_tpl_id:"",
        public_parent_id:"",
      showres: false,
      dialogCadVisible:false,
      cadNode:null,
      cadno:'',
      gutters: [20, 25, 25, 33, 50],
      viewShowNode: null,
      showHistory: false,
      historyList: [],
      defaultProps: {
        children: 'children',
        label: 'department_name'
      },
      listLoading: false,
      treedata: [],
      treeloading: false,
      treeExpand: [],
      stationloading: false,
      activeNames: ['0', '1', '2'],
      dialogVisible: false,
      dialogVisibleDetail:false,
      table: false,
      dialog: false,
      dialogDetail: false,
      loading: false,
      gridData: [],


      formLabelWidth: '80px',
      timer: null,
      tableKey: 0,
      openfile: ['0', '1'],
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,


      downloadLoading: false,
      rightEle: null,
      showReviewer: false,
      sortOptions: [
        { label: '*', key: '0' },
        { label: 'PDF', key: '1' },
        { label: 'word/Excel/PPT', key: '2' },
        { label: 'JPG/Bmp', key: '3' },
        { label: 'Zip/Rar', key: '4' },
        { label: 'Dwg/dwt', key: '5' },
        { label: 'Itp/stp/3ds/stl', key: '6' },
        { label: 'Eip', key: '7' }

      ],
      rangelist: [
        { label: '全部', key: '0' },
        { label: '文件内', key: '1' },
        { label: this.$t('bs.fileName'), key: '2' }
      ],

      gxlist: [],
      upheaders: {},
      updata: {},
      station_id: '',
      showup: false,
      copyItem: null,
      viewLoading: false,
      selectHistoryKey: '',
      resetStationData: null,
      depts: [],
      lines: [],
      costs: [],
      technology_type_option: [],
      dev_type_option: [],
      supplierList: []
    }
  },
  watch: {
    '$store.state.advancedSearch.listQuery.dept_id': {
      async handler(newval, oldval) {
        if (oldval && newval != oldval) {
          console.log('旧值', oldval)
          this.$store.state.advancedSearch.form.cost_id = ''
          this.$store.state.advancedSearch.form.line_id = ''
        }

        if (newval) {
          const tempCosts = await getcost(newval)
          console.log(tempCosts)
          this.costs = tempCosts.data.items
          console.log('当前选选中的产线', this.$store.state.advancedSearch.form.line_id)
        }
      }
    },
    '$store.state.advancedSearch.listQuery.cost_id': {
      async handler(newval, oldval) {
        if (oldval && newval != oldval) {
          console.log('有旧值')
          this.$store.state.advancedSearch.form.line_id = ''
        }
        if (newval) {
          const tempCosts = await getlines(newval)
          this.lines = tempCosts.data.items
          console.log('当前选选中的产线', this.$store.state.advancedSearch.form.line_id)
        }
      }
    }
  },
  mounted() {
    Date.prototype.Format = function(formatStr) {
      var str = formatStr
      var Week = ['日', '一', '二', '三', '四', '五', '六']

      str = str.replace(/yyyy|YYYY/, this.getFullYear())
      str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100))

      str = str.replace(/MM/, this.getMonth() > 9 ? this.getMonth().toString() : '0' + (this.getMonth() + 1))
      str = str.replace(/M/g, this.getMonth())

      str = str.replace(/w|W/g, Week[this.getDay()])

      str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate())
      str = str.replace(/d|D/g, this.getDate())

      str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours())
      str = str.replace(/h|H/g, this.getHours())
      str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes())
      str = str.replace(/m/g, this.getMinutes())

      str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds())
      str = str.replace(/s|S/g, this.getSeconds())

      return str
    }
    this.getList()
    this.geShoucang()
    getDepartment().then((res) => {
      console.log('部门', res.data.items)
      this.depts = res.data.items
    })
    getTechonlogyCat().then((option) => {
      if (!option.data.items) {
        option.data.items = []
      }
      option.data.items.unshift({
        id: '', technology_name: '无', parent_id: '0'
      })
      this.technology_type_option = option.data.items.filter(obj => obj.parent_id === '0')
      console.log('工艺类型', this.technology_type_option)
    })
    fetchDict('dev_type').then((res) => {
      if (res.data.items) {
        this.dev_type_option = res.data.items
      }
    })
    fetchDict('供应商').then((res) => {
      if (res.data.items) {
        this.supplierList = res.data.items.filter(item=>item.dict_key)
      }
    })
    getStationAttr().then((res) => {
      if (!res.data.items) {
        res.data.items = []
      }
      console.log('公有属性', res)
      res.data.items.forEach((item) => {
        if (item.inc_type == '2') {
          if (item.list_val) {
            item.list_val = JSON.parse(item.list_val)
          } else {
            item.list_val = []
          }
        }
        item['attr_id'] = item['id']
        item['attr_val'] = ''
      })

      this.$store.state.advancedSearch.station_attr = _.cloneDeep(res.data.items)
      this.$store.state.advancedSearch.form.attrinfo = res.data.items
    })

      //获取公用模板
      getPublicTpl({id:this.inc_type}).then((res)=>{
          this.public_tpl_id=res.data.doc_id;
          this.public_parent_id=res.data.parent_id
          this.getPublicList(parseInt(this.public_tpl_id),0,parseInt(this.public_parent_id))
          console.log("公用模板id",res)

      })
    let localView=localStorage.getItem("fileViewCache");
    if(localView){
      this.$store.state.fileView.recentViews=JSON.parse(localView);
    }
    let localViewFixed=localStorage.getItem("fileViewCacheFixed");
    if(localViewFixed){
      this.$store.state.fileView.recentViewsFixed=JSON.parse(localViewFixed);
    }
  },
  methods: {
    cancelCad()
    {
      this.cadno='';
      this.dialogCadVisible = false
    },
    subCad(){
      if(!this.cadno)
      {
        this.$message.error("请输入图纸号")
        return;
      }
      if(!this.$store.state.fileView.station_id)
      {
        this.$message.error("请选择工位")
        return;
      }
      console.log('节点',this.$store.state.fileView.station_id,this.cadNode.id,this.cadno)
      addcad({
        station_id:parseInt(this.$store.state.fileView.station_id),
        doc_id:parseInt(this.cadNode.id),
        name:this.cadno
      }).then((res)=>{
        if(res.code==0){
          this.$message.success("添加成功")
          this.dialogCadVisible=false;
          this.cadno='';
          this.$nextTick(()=>{
            let parent = this.getTreeNodeById(this.$store.state.fileView.fileTree, this.cadNode.id)
            if(!res.data['0'].promise)
            {
              res.data['0'].promise={
                is_read:1,
                is_write:1,is_down:1,
                is_share:0,
              }
            }
            parent.newChildren.push(res.data[0])
            this.$refs.fileViewRef.refirsh()
          })
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    unCollect(key)
    {

      let node = this.$store.state.fileView.myCollection[key];
      let file = {
        id:node.file_id,
        station_id:node.station_id,
        path:''
      }

      this.shouchangFile(file)

    },
    fixrecent(key,val)
    {
      if(val==1)
      {
        if(this.$store.state.fileView.recentViewsFixed.length>=5)
        {
          this.$message.error("最多固定五条记录！");
          return;
        }
        this.$store.state.fileView.recentViewsFixed.unshift(_.cloneDeep(this.$store.state.fileView.recentViews[key]))
        this.$store.state.fileView.recentViews.splice(key,1)
      }else{
        this.$store.state.fileView.recentViews.unshift(_.cloneDeep(this.$store.state.fileView.recentViewsFixed[key]))
        this.$store.state.fileView.recentViewsFixed.splice(key,1)
      }
    },
    delListVal(){
      localStorage.removeItem("fileViewCache");
      localStorage.removeItem("fileViewCacheFixed");
      this.$store.state.fileView.recentViews=[];
      this.$store.state.fileView.recentViewsFixed=[];
    },
    printFile() {

    },
    openDetail(){
      this.dialogDetail=true
      var station =  this.$store.state.fileView.stationList.filter((item)=>{
        return item.id==this.$store.state.fileView.station_id
      })
      console.log(this.$refs)
      this.$nextTick(()=>{
        this.$refs.stationDetailRef.openStation(station[0]);
      })

    },
    handleFilterReset() {
      this.$store.state.advancedSearch.listQuery= {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        technology_type:[],
        where: {}
      }
      this.$store.state.advancedSearch.form.attrinfo = _.cloneDeep(this.$store.state.advancedSearch.station_attr)
      this.$store.state.advancedSearch.techonlogyList=[];
      this.$store.state.advancedSearch.selected_num=0;
      this.$store.state.advancedSearch.listQuery.selectedList=[];
      if(this.$refs.technologySelectRef){
        this.$refs.technologySelectRef.initData()
      }
      //
      // this.$refs.technologySelectRef2.initData()


    //  this.handleFilter()
    },
    handleFilter() {
      this.$emit("ok");
      return;
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.$store.state.advancedSearch.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)

      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          console.log('查询', listkeys[i], isNaN(listkeys[i]))
          let operator = '='
          let value = this.listQuery[listkeys[i]]
          if (!this.queryMap[listkeys[i]]) {
            if (isNaN(listkeys[i])) {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          } else {
            if (this.queryMap[listkeys[i]] == 'like') {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (this.queryMap[listkeys[i]] == 'in') {
              operator = 'in'
              console.log("有in，需要组合2",this.listQuery[listkeys[i]])
              value = this.listQuery[listkeys[i]].join(",")
            }


            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          }
        }
      }
      let querym = []
      const keys = Object.keys(queryParma)
      for (var i = 0; i < keys.length; i++) {
        queryParma[keys[i]].map((item) => {
          querym.push(item)
        })
      }


      const parma = { data: querym }
      console.log('查询参数2', querym)

      const attinfo = this.$store.state.advancedSearch.form.attrinfo

      const att = []
      attinfo.map((item) => {
        if (item.attr_val) {
          let op = '='
          const filed = item.attr_id
          let value = item.attr_val
          if (item.list_val.length == 0) {
            op = 'like'
            value = '%' + value + '%'
          }
          att.push({ field: filed, value: value, operator: op })
        }
      })
      parma['attr'] = att

      this.list = []

      this.listQuery['where'] = queryParma

      this.getDept2(parma)
    },
    getDept2(listQuery) {
      this.$store.state.fileView.stationList = []
      this.$store.state.fileView.fileTree = {}
      this.$store.state.fileView.station_id = ''
      this.stationloading = true

      console.log("查询in",listQuery)
      advSearch(listQuery).then(response => {
        console.log('搜出的工站', response)
        if (response.data) {
          response.data.forEach((item) => {
            item.search_name = item.station_number + item.station_name
          })
          console.log(response.data)
          this.$store.state.fileView.stationList = response.data
          this.resetStationData = _.cloneDeep(response.data)
        }
        this.stationloading = false
      }).catch((res) => {
        this.stationloading = false
      })
    },
    copyshareUrl() {
      var element = this.createElement(this.shareurl)
      element.select()
      element.setSelectionRange(0, element.value.length)
      document.execCommand('copy')
      element.remove()
      this.$message.success('已复制到剪贴板！')
    },
    createElement(text) {
      var isRTL = document.documentElement.getAttribute('dir') === 'rtl'
      var element = document.createElement('textarea')
      // 防止在ios中产生缩放效果
      element.style.fontSize = '12pt'
      // 重置盒模型
      element.style.border = '0'
      element.style.padding = '0'
      element.style.margin = '0'
      // 将元素移到屏幕外
      element.style.position = 'absolute'
      element.style[isRTL ? 'right' : 'left'] = '-9999px'
      // 移动元素到页面底部
      const yPosition = window.pageYOffset || document.documentElement.scrollTop
      element.style.top = `${yPosition}px`
      // 设置元素只读
      element.setAttribute('readonly', '')
      element.value = text
      document.body.appendChild(element)
      return element
    },
    handleFileFilter() {
      this.queryfile.doc_id = parseInt(this.doc_id)
      this.queryfile.station_id = parseInt(this.$store.state.fileView.station_id)
      this.queryfile.parent_id = parseInt(this.parent_id)
      this.queryfile.keyword = this.$store.state.advancedSearch.listQuery.keyword
      getSearch(this.queryfile).then((res) => {
        console.log(res)
        this.mergeChildren(res.data[0])
        this.$store.state.fileView.fileTree = res.data[0]
        this.$refs.fileViewRef.refirsh()
      })
    },
    selectHistore() {

    },
    rightSelectHistore() {

    },
    jumpTorecent(item) {
      this.$store.state.fileView.fileTree = _.cloneDeep(item.path)
      this.$refs.fileViewRef.refirsh()
    },
    jumpToCollection(item) {

      this.$store.state.fileView.fileTree = _.cloneDeep(JSON.parse(item.path))
      this.$refs.fileViewRef.refirsh()
    },
    rendered() {
      console.log('预览加载完成')
      this.viewLoading = false
    },
    copyFile(node) {
      this.copyItem = node
      this.$message.info('已经复制到剪切板')
    },
    getShareUrl(node) {
      this.loading = true
      const data = {
        file_id: node.id,
        inc_type: node.inc_type == 'dir' ? 'dir' : 'file',
        station_id: this.$store.state.fileView.station_id
      }
      getShareUrl(data).then((res) => {
        this.loading = false
        console.log('分享', res)
        this.shareurl = res.data
        this.showShare = true
      }).catch(() => {
        this.loading = false
      })
    },
    shouchangFile(node) {
      shoucang({ file_id: node.id, station_id: node.station_id, path: JSON.stringify(this.$store.state.fileView.fileTree) }).then((res) => {
        // 刷新收藏
        this.geShoucang()
        this.$message.success(res.msg)
      })
    },
    getHistoryFile(node) {
      getHistory(node.id).then((res) => {
        this.historyList = []
        console.log('历史', res)
        if (!res.data || res.data.length == 0) {
          this.$message.error('此文件没有历史版本')
          return
        }
        res.data.forEach((item) => {
          item.inc_type = node.inc_type
          item.id = item.file_id
        })
        this.showHistory = true
        this.historyList = res.data || []
        console.log(this.historyList)
      })
    },
    addCad(node){
        this.cadNode=node
        this.dialogCadVisible=true;
    },

    viewFile(node) {
      console.log('想看权限',node)
      if(node.promise&&node.promise.is_read===0)
      {
        this.$message.error('您没有查看此文件的权限')
        return
      }
      var has = this.$store.state.fileView.recentViews.filter(item => item.id == node.id)
      if (!has || has.length == 0) {
        if ((this.$store.state.fileView.recentViews.length+this.$store.state.fileView.recentViewsFixed.length) >= 10) {
          this.$store.state.fileView.recentViews = this.$store.state.fileView.recentViews.splice(this.$store.state.fileView.recentViews.length-1)
        }
        this.$store.state.fileView.recentViews.unshift({ id: node.id, name: node.name, path: _.cloneDeep(this.$store.state.fileView.fileTree) })
        localStorage.setItem("fileViewCache",JSON.stringify(this.$store.state.fileView.recentViews))
        localStorage.setItem("fileViewCacheFixed",JSON.stringify(this.$store.state.fileView.recentViewsFixed))
      }
      this.viewShowNode = { type: node.inc_type, href: '' }
      if(node.inc_type=='EPM'){
        getEmpData(this.$store.state.fileView.station_id).then((res)=>{
          this.viewShowNode = { type: node.inc_type, href: res.data }
          console.log("展示EPM",this.viewShowNode)

          this.showReviewer = true
          this.viewLoading = false

        })
      }else if(node.inc_type=='SPM')
      {
        var inc_type='spm';
        getSpmData(inc_type).then((res)=>{
          if(res.data){
            window.open(res.data);
          }
        })
      }else if(node.inc_type=='MIS+')
      {

       inc_type='mis'
        getSpmData(inc_type).then((res)=>{
          if(res.data){
            this.$refs.misDetail.show(res.data)
          }
        })
      }else if(node.inc_type=='cad')
      {

        var element = this.createElement(node.name)
        element.select()
        element.setSelectionRange(0, element.value.length)
        document.execCommand('copy')
        element.remove()
            if(node.path){
              window.open(node.path);
            }

      }else if(node.inc_type=='Process Key parts')
      {
        this.$refs.sparedetail.show(this.$store.state.fileView.station_id);

      }else if(node.inc_type=='reuse/relocation record')
      {
        this.$refs.srelocationView.show(this.$store.state.fileViewSearch.station_id);
      }else if(node.inc_type=='process/parts change list')
      {
        this.$refs.partsview.show(this.$store.state.fileViewSearch.station_id);
      }else{
        //组装加密url
        var token =getToken();
        var previewUrl=process.env.VUE_APP_BASE_URL+'/api/devfile/down?file_id='+node.id+"&Accesstoken="+token+"&fullfilename="+node.name;

        console.log('previewUrl',previewUrl)

        window.open("http://cngvm00100.apac.bosch.com:8012/onlinePreview?url="+encodeURIComponent(Base64.encode(previewUrl)));

        // viewBlobFile({ file_id: node.id }).then((response) => {
        //   const blob = response
        //   if (blob && blob.size === 0) {
        //     this.$message.error('内容为空，无法预览')
        //     this.viewLoading = false
        //     return
        //   }
        //
        //   // 兼容一下 入参不是 File Blob 类型情况
        //   var binaryData = []
        //   binaryData.push(response)
        //   this.viewShowNode.href = window.URL.createObjectURL(new Blob(binaryData))
        //   this.showReviewer = true
        //   // if(node.inc_type=='pptx')
        //   // {
        //   //
        //   //   this.$nextTick(()=>{
        //   //     console.log("获取到节点",$("#pptxview"));
        //   //
        //   //
        //   //     $("#pptxview").pptxToHtml({
        //   //       pptxFileUrl:  this.viewShowNode.href, //pptx文件地址
        //   //       slidesScale: "100%",
        //   //     });
        //   //   })
        //   //
        //   // }
        //
        // })
      }

    },
    pasteFile(node) {
      console.log('粘贴的目标', node)
      if (!this.copyItem) {
        this.$message.info('请先复制文件')
        return
      }
      if (this.copyItem.parent_id == node.id) {
        this.$message.info('同一目录下无法使用粘贴')
        return
      }
      var station_id=this.$store.state.fileView.station_id;
      var ispublic= this.getTreeNodeById(this.$store.state.fileView.publicTree, node.id)
      if(ispublic){
        station_id=0;
      }
      pasteToDir({ station_id:station_id, file_id: this.copyItem.id, template_id: node.id }).then((res) => {
        this.$message.success('粘贴成功')
        var node = res.data
        var parent = this.getTreeNodeById(this.$store.state.fileView.fileTree, node.doc_id)
        var hasNode = this.getTreeNodeById(this.$store.state.fileView.fileTree, node.id)
        if(!parent){
          parent = this.getTreeNodeById(this.$store.state.fileView.publicTree, node.doc_id)
          hasNode = this.getTreeNodeById(this.$store.state.fileView.publicTree, node.id)
        }
        console.log('上级', parent, hasNode)
        if (!hasNode) {
          if (!parent.newChildren) {
            parent.newChildren = []
          }
        node.promise=_.cloneDeep(parent.promise)
          parent.newChildren.push(node)
          this.$refs.fileViewRef.refirsh()
        }
      })
    },
    deleteFile(node) {
      delFile({ file_id: node.id }).then(() => {
        this.$message.success('删除成功')
        var parent = this.getTreeNodeById(this.$store.state.fileView.fileTree, node.doc_id)
        if(!parent){
          parent = this.getTreeNodeById(this.$store.state.fileView.publicTree, node.doc_id)
        }

        console.log('是否公用', this.$store.state.fileView.publicTree.selectKey)
        if (!parent.newChildren) {
          parent.newChildren = []
        }
        parent.newChildren = parent.newChildren.filter((item) => {
          return item.id != node.id
        })
        this.$refs.fileViewRef.refirsh()
      })
    },
    dowloadFile(node) {
      downBlobFile({ file_id: node.id }, node.name)
    },
    selectStation(key) {
      console.log("是否在加载2",this.listLoading)
      if(this.listLoading){
        return;
      }
      this.listLoading=true;
      this.$store.state.fileView.stationList.map(async (item, i) => {
        if (key !== i) {
          this.$store.state.fileView.stationList[i]['selected'] = false
        } else {
          this.$store.state.fileView.stationList[i]['selected'] = true
          this.$store.state.fileView.station_id = item.id
          this.doc_id=parseInt(item.mea_id)

          //获取parent_id
          const docItem = await getTemplateRoot(this.doc_id)
            console.log("docItem",docItem)
            this.parent_id = parseInt(docItem.data.id)


          this.getFileList(this.doc_id, item.id, this.parent_id)
          this.$refs.fileviewTree.setCurrentKey(item.line_id)


          console.log('当时',item.line_id);

          let node = this.getTreeNodeById2(this.treedata[0],item.line_id)

          this.openParent(this.getTreeNodeById2(this.treedata[0],item.line_id))


          // this.getFileList(1, item.id, this.parent_id)
        }
      })
      this.$store.state.fileView.stationList = _.cloneDeep(this.$store.state.fileView.stationList)
    },
    openParent(treeNode){
      if(treeNode.parent_id>0)
      {
        var parent = this.getTreeNodeById2(this.treedata[0],treeNode.parent_id)
        let parent_tode=this.$refs.fileviewTree.getNode(treeNode.parent_id)
        console.log("父节点",parent_tode)
        parent_tode.expand();
        if(parent.parent_id>0)
        {
          this.openParent(parent)
        }
      }
    },

    mergeChildren(tree,parent) {
        // console.log("继承权限",tree,parent)
      if (!tree.children) {
        tree['children'] = []
      }
      if (!tree.filelist) {
        tree['filelist'] = []
      }
      if(!tree.width)
      {
        tree.width=200;
      }

      if(!tree.promise&&parent&&parent.promise)
      {
          console.log("继承权限")
          tree.promise=parent.promise
      }


      tree['newChildren'] = tree.children.concat(tree.filelist)
      tree['selectKey'] = null
      for (var i = 0; i < tree.newChildren.length; i++) {
        this.mergeChildren(tree.newChildren[i],tree)
      }
    },
      getPublicList(doc_id = 1, station_id, parent_id) {
          this.$store.state.fileView.fileTree = {}
          this.listLoading = true
          fetchTree({
              doc_id: doc_id,
              station_id: parseInt(station_id),
              parent_id: parent_id
          }, '/api/station/gettemplatelist').then(response => {
              if (response.data) {
                  this.mergeChildren(response.data[0])
                  this.$store.state.fileView.publicTree = response.data[0]
                  console.log("公用树",response.data[0])
                  // this.total = response.data.count
              }
              this.listLoading = false
          })
      },
    getFileList(doc_id = 1, station_id, parent_id) {
      this.$store.state.fileView.fileTree = {}
      this.listLoading = true
      fetchTree({
        doc_id: doc_id,
        station_id: parseInt(station_id),
        parent_id: parent_id
      }, '/api/station/gettemplatelist').then(response => {
        if (response.data) {
          this.mergeChildren(response.data[0])
          this.$store.state.fileView.fileTree = response.data[0]
          // this.total = response.data.count
        }
        this.$nextTick(()=>{
          this.listLoading = false
        })

      })
    },
    geShoucang() {
      console.log('用户信息', this.$store.state.user)

      const listQuery = {
        page_no: 1,
        limit: 100,
        sort: 'id desc',
        where: { and: [{ field: 'user_id', operator: '=', value: this.$store.state.user.user_id }] }
      }
      this.$store.state.fileView.myCollection=[];
      fetchList(listQuery, 'sl_view_collect').then(response => {
        console.log('回复', response)
        if (response.data) {
          this.$store.state.fileView.myCollection = response.data.items.filter(item=>item.name!="")
        }
      }).catch((e) => {
        this.treeloading = false
      })
    },
    getList() {
      this.treeloading = true
      fetchTree(this.listQuery, '/api/auth/getdeptlist').then(response => {
        if (response.data) {
          this.treedata = response.data
          this.treeExpand = response.data.map((item) => {
            return item.id
          })
        }
        this.treeloading = false
      }).catch((e) => {
        this.treeloading = false
      })
    },
    handleUpload(item) {
      this.upheaders = {
        AccessToken: getToken()
      }
      if (!this.$store.state.fileView.station_id) {
        for (var i = 0; i < this.$store.state.fileView.stationList.length; i++) {
          if (this.$store.state.fileView.stationList[i].selected) {
            this.$store.state.fileView.station_id = this.$store.state.fileView.stationList[i].id
          }
        }
      }
      var station_id=this.$store.state.fileView.station_id;
      var ispublic= this.getTreeNodeById(this.$store.state.fileView.publicTree, item.id)
      if(ispublic){
        station_id=0;
      }
      this.updata = {
        doc_id: item.id,
        station_id: station_id
      }
      this.$refs.uploadRef.$refs['upload-inner'].$refs.input.click()
    },
    getTreeNodeById2(tree, id) {
      console.log("数据",tree)
      let data = null
      if (!tree.children) {
        tree.children = []
      }
      if(tree.id==id)
      {
        return  tree;
      }
      for (var i = 0; i < tree.children.length; i++) {
        var item = tree.children[i]
        if (item.id == id) {
          data = item
        }
        if (data) {
          break
        }
        if (item.children) {
          data = this.getTreeNodeById2(item, id)
        }
        if (data) {
          break
        }
      }
      return data
    },
    getTreeNodeById(tree, id) {
      let data = null
      if (!tree.newChildren) {
        tree.newChildren = []
      }
      for (var i = 0; i < tree.newChildren.length; i++) {
        var item = tree.newChildren[i]
        if (item.id == id) {
          data = item
        }
        if (data) {
          break
        }
        if (item.newChildren) {
          data = this.getTreeNodeById(item, id)
        }
        if (data) {
          break
        }
      }
      return data
    },
    handleSuccess(response) {
      var node = response.data[0]
      var parent = this.getTreeNodeById(this.$store.state.fileView.fileTree, node.doc_id)
      var hasNode = this.getTreeNodeById(this.$store.state.fileView.fileTree, node.id)

      if(!parent){
        parent = this.getTreeNodeById(this.$store.state.fileView.publicTree, node.doc_id)
        hasNode = this.getTreeNodeById(this.$store.state.fileView.publicTree, node.id)
      }
      console.log('上传成功',parent)
      if (!hasNode) {
        if (!parent.newChildren) {
          parent.newChildren = []
        }
      node.promise=_.cloneDeep(parent.promise)
          parent.newChildren.push(node)

      }
      this.$refs.fileViewRef.refirsh()
      this.showup = false
    },
    getDept(listQuery) {
      this.$store.state.fileView.stationList = []
      this.$store.state.fileView.fileTree = {}
      this.$store.state.fileView.station_id = ''
      this.stationloading = true
      fetchList(listQuery, 'sl_view_station').then(response => {
        if (response.data && response.data.items) {
          response.data.items.forEach((item) => {
            item.search_name = item.station_number + item.station_name
          })
          console.log(response.data.items)
          this.$store.state.fileView.stationList = response.data.items
          this.resetStationData = _.cloneDeep(response.data.items)
        }
        this.stationloading = false
      }).catch((res) => {
        this.stationloading = false
      })
    },
    handleNodeClick(data) {
      if (data.department_type == '部门') {
        const listQuery = {
          'page_no': 1,
          'limit': 1000,
          'sort': 'id desc',
          'where': {
            'and': [
              {
                'field': 'dept_id',
                'operator': '=',
                'value': data.id
              }
            ]
          }
        }
        this.$store.state.advancedSearch.listQuery.line_id='';
        return;
    //    this.getDept(listQuery)
      }
      if (data.department_type == '价值流') {
        const listQuery = {
          'page_no': 1,
          'limit': 1000,
          'sort': 'id desc',
          'where': {
            'and': [
              {
                'field': 'cost_id',
                'operator': '=',
                'value': data.id
              }
            ]
          }
        }
        this.$store.state.advancedSearch.listQuery.line_id='';
        return;
       // this.getDept(listQuery)
      }
      if (data.department_type == '产线') {
        const listQuery = {
          'page_no': 1,
          'limit': 1000,
          'sort': 'station_number asc',
          'where': {
            'and': [
              {
                'field': 'line_id',
                'operator': '=',
                'value': data.id
              }
            ]
          }
        }
        this.$store.state.advancedSearch.listQuery.line_id=data.id

        this.getDept(listQuery)
      }
    },
    handleCloseDetail() {
      console.log("调用了关闭")
      this.dialogDetail = false
      this.dialogVisibleDetail = false
    },
    handleClose() {
      this.dialog = false
      this.dialogVisible = false
    },
    dbshow() {
      this.dialogVisible = true
    },
    andleClose(done) {
      if (this.loading) {
        return
      }
      this.$confirm('确定要提交表单吗？')
        .then(_ => {
          this.loading = true
          this.timer = setTimeout(() => {
            done()
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false
            }, 400)
          }, 2000)
        })
        .catch(_ => {
        })
    },
    cancelFormDetail(){
      this.dialogDetail=false;
    },
    cancelForm() {
      this.loading = false
      this.dialog = false

      clearTimeout(this.timer)
      this.$emit("close");
    },
    handleStationFilter() {
      this.stationloading = true
      this.$store.state.fileView.stationList = []
      this.$store.state.fileView.station_id = ''
      this.handleFilter()
    },
    // handleFilter() {
    //   var node = this.getTreeNodeById(this.$store.state.fileView.fileTree, '11')
    //   this.$store.state.advancedSearch.listQuery.page = 1
    // },
    resize() {

    }
  }
}
</script>

<style scoped>
.my-resize {
  display: inline-block;
  position: static;
  border: none;
  border-right: 5px solid #dddddd;
}

.my-resize /deep/ .handle-mr {
  border: none;
  background: #eeeeee;
  height: 100%;
  top: 5px;
  width: 5px;
  right: -5px;
  display: block !important;
}
.viewbox{
  width: 100%; height: 60vh;display:flex;overflow-y: scroll;align-items: center;justify-content: center;
}
.viewbox /deep/ canvas{
  position: static !important;
}

.tree-container {
  margin-top: 8px;
}

.upbox {
  position: fixed;
  top: 0px;
  right: 0px;
  transition-property: right;
  transition-duration: 1s;
  transition-timing-function: ease-in-out;
  transition-delay: .3s;
}

.boxshow {
  right: 0px;
}

.boxhide {
  right: -500px;
}

.tree-container /deep/ .el-tree-node {
  position: relative;
  padding-left: 13px;
}

.tree-container /deep/ .el-tree-node:before {
  width: 1px;
  height: 100%;
  content: '';
  position: absolute;
  top: -38px;
  bottom: 0;
  left: 0;
  right: auto;
  border-width: 1px;
  border-left: 1px solid #b8b9bb;
}

.tree-container /deep/ .el-tree-node:after {
  width: 13px;
  height: 13px;
  content: '';
  position: absolute;
  left: 0;
  right: auto;
  top: 12px;
  bottom: auto;
  border-width: 1px;
  border-top: 1px solid #b8b9bb;
}

.tree-container /deep/ .el-tree > .el-tree-node:before {
  border-left: none;
}

.tree-container /deep/ .el-tree > .el-tree-node:after {
  border-top: none;
}

.tree-container /deep/ .el-tree .el-tree-node:last-child:before {
  height: 50px;
}

.tree-container /deep/ .el-tree .el-tree-node__content {
  color: #000;
  font-size: 14px;
  padding-left: 0 !important;
}

.tree-container /deep/ .el-tree .el-tree-node__children {
  padding-left: 11.5px;
}

.tree-container /deep/ .el-tree .el-tree-node__content > label.el-checkbox {
  margin: 0 5px 0 5px !important;
}

.tree-container /deep/ .el-tree .el-tree-node__expand-icon {
  position: relative;
  z-index: 99;
}

.tree-container /deep/ .el-tree .el-tree-node__expand-icon.is-leaf {
  display: none;
}

.tree-container /deep/ .el-tree .leaf-node-line {
  width: 23px;
  height: 13px;
  content: '';
  position: absolute;
  left: 13px;
  right: auto;
  top: 12px;
  bottom: auto;
  border-width: 1px;
  border-top: 1px solid #b8b9bb;
}

.tree-container /deep/ .el-tree .el-tree-node__content:has(.is-leaf) {

  margin-left: 24px !important;
}

.el-form-item__label {
  padding: 0px !important;
}

.el-drawer__header {
  margin: 0px !important;
  padding: 16px !important;
}

.demo-drawer {
  width: 300px;
}

.file-view-box {
  height: calc(100vh - 166px);
}

.filter-container {
  border-bottom: 1px solid #cccccc;
  padding: 10px 3px 0px 3px;
  overflow: hidden;
  height: 50px;
}

.file-button-box {
  height: 36px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  font-size: 12px;
  cursor: pointer;
  user-select: none;
}

.file-button-box-selected {
  background: #1067de;
  color: #ffffff !important;
}

.gwbox:hover {
  background: #dcdcdc;
}

.file-button-box:hover {
  background: #dcdcdc;
}

.file-button-box-hover {
  background: #dcdcdc;
}

.file-button-img-box {
  width: 36px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.file-button-title {
  display: flex;
  align-items: center;
  flex: 1;
}

.file-button-img-DWI {
  background-position: 0px -1800px;
}
.file-button-img-EPM {
  background-position: 0px -1850px;
}
.file-button-img-SPM {
  background-position: 0px -1900px;
}
.file-button-img {
  width: 16px;
  height: 16px;
  background: url('/static/icons-small.png') no-repeat;
}

.file-button-right {
  font-size: 14px;
  width: 20px;
}

.components-container {
  position: relative;
  margin: 0px;
  border: 2px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.left-container {
  /*background-color: #F38181;*/
  overflow-y: auto;
  height: 100%;
  padding: 3px;
}

/* 自定义滚动条样式 */


.right-container {
  background-color: #FCE38A;
  height: 200px;
}

.top-container {
  background-color: #FCE38A;
  width: 100%;
  height: 100%;
}

.bottom-container {
  width: 100%;
  background-color: #95E1D3;
  height: 100%;
}
</style>
